//
//  imageShowBrowser.m
//  FCTools
//
//  Created by WJC on 2018/10/29.
//  Copyright © 2018 wjc. All rights reserved.
//

#import "imageShowBrowser.h"
#import "WJCDefine.h"
#import "imageCollectionViewCell.h"
#import "UIView+viewExtension.h"
#import "Masonry.h"
#import "UIImageView+WebCache.h"
#import "imageCollectionViewCell.h"

@interface imageShowBrowser() <UICollectionViewDelegate, UICollectionViewDataSource,UIGestureRecognizerDelegate,UICollectionViewDelegateFlowLayout>
/**图片数组*/
@property (nonatomic,strong)NSMutableArray *imageArr;
/**图片数组*/
@property (nonatomic,strong)NSMutableArray *smalllImage;
/**图片呈像*/
@property (nonatomic,strong)UICollectionView *collection;
@property (nonatomic,strong)UICollectionViewFlowLayout* flowLayout;

/**页数*/
@property (nonatomic,assign)int  page;
/**点击视图*/
@property (nonatomic,strong)UIView *clickView;
/**父视图*/
@property (nonatomic,strong)UIView *superView;

@end
@implementation imageShowBrowser
-(instancetype)initWithFrame:(CGRect)frame andImageArr:(NSArray *)arr andsmallImage:(NSArray*)smallImage andClickView:(UIView *)clickView andImgSuperView:(UIView *)imgSuperView andIndex:(NSInteger)index{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.frame=CGRectMake(0, 0, WJCScreenW, WJCScreenH);
        _clickView=clickView;
        _superView=imgSuperView;
        _imageArr=[arr mutableCopy];
        _smalllImage=[smallImage mutableCopy];
        _flowLayout=[[UICollectionViewFlowLayout alloc] init];
        [_flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
        _flowLayout.itemSize=CGSizeMake(WJCScreenW, WJCScreenH);
        _flowLayout.minimumInteritemSpacing=0;
        _flowLayout.sectionInset=UIEdgeInsetsMake(0, 0, 0, 0);
        _collection = [[UICollectionView alloc]initWithFrame:self.frame collectionViewLayout:_flowLayout];
        [self addSubview:_collection];
        [_collection registerClass:[imageCollectionViewCell class] forCellWithReuseIdentifier:@"imageCell"];
        for(int i=0;i<arr.count;i++){
            [_collection registerClass:[imageCollectionViewCell class] forCellWithReuseIdentifier:[NSString stringWithFormat:@"imageCell%d",i] ];
        }
        [_collection setBackgroundColor:[UIColor blackColor]];
        [_collection mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.and.left.bottom.right.mas_equalTo(0);
        }];
        _collection.delegate=self;
        _collection.dataSource=self;
        [self.collection setContentOffset:CGPointMake((WJCScreenW+10)*index, 0)];
        
            //        _collection.pagingEnabled=YES;
        if (_imageArr.count>1) {
            _label=[[UILabel alloc]initWithFrame:CGRectMake(WJCScreenW*0.5-20, 40, 40, 20)];
            _label.font=font15;
            _label.textAlignment=NSTextAlignmentCenter;
            _label.backgroundColor=[UIColor lightGrayColor];
            _label.textColor=[UIColor whiteColor];
            _label.layer.cornerRadius=10;
            _label.layer.masksToBounds=YES;
            _page=(int)index;
            _label.text=[NSString stringWithFormat:@"%d/%ld",_page+1,_imageArr.count];
            [self addSubview:_label];
        }
        UITapGestureRecognizer *tap1=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap:)];
        tap1.numberOfTapsRequired=1;
        [self addGestureRecognizer:tap1];
    };
    return self;
}
-(void)showView{
    CGRect frame;
    if (_clickView) {
        frame = [_clickView.superview convertRect:_clickView.frame toView:_superView];
        UIWindow * window=[[[UIApplication sharedApplication] delegate] window];
        UIImageView *image=[[UIImageView alloc]initWithFrame:frame];
        if (!((UIImageView*)_clickView).image) {
            image.image=[UIImage imageNamed:@"browser"];
        }
        else
            image.image=((UIImageView*)_clickView).image;
        image.contentMode=UIViewContentModeScaleAspectFit;
        [[UIApplication sharedApplication].keyWindow addSubview:image];
        [UIView animateWithDuration:0.3 animations:^{
            image.frame=self.frame;
        }completion:^(BOOL finished) {
            [window.rootViewController.view addSubview:self];
            [image removeFromSuperview];
        }];
        
    }
    else{
        frame=CGRectMake(0, 0, WJCScreenW, WJCScreenH);
        UIWindow * window=[[[UIApplication sharedApplication] delegate] window];
        UIImageView *image=[[UIImageView alloc]initWithFrame:frame];
        image.image=((UIImageView*)_clickView).image;
        image.contentMode=UIViewContentModeScaleAspectFit;
        [[UIApplication sharedApplication].keyWindow addSubview:image];
        [UIView animateWithDuration:0.3 animations:^{
            image.frame=self.frame;
        }completion:^(BOOL finished) {
            [window.rootViewController.view addSubview:self];
            [image removeFromSuperview];
        }];
        
    }
    
}
-(void)removeWithView:(UIImageView*)image{
    CGRect frame=CGRectMake(0, 0, 0, 0);
    for (UIView*view in _clickView.superview.subviews) {
        if ([view isKindOfClass:[UIImageView class]]) {
            if (view.tag==_page||view.tag-1000==_page) {
                frame = [view.superview convertRect:view.frame toView:_superView];
                UIImageView *imageView=[[UIImageView alloc]initWithFrame:image.frame];
                imageView.contentMode=UIViewContentModeScaleAspectFit;
                imageView.image=((UIImageView*)view).image;
                [_superView addSubview:imageView];
                [self removeFromSuperview];
                [UIView animateWithDuration:0.3 animations:^{
                    imageView.frame=frame;
                }completion:^(BOOL finished) {
                    [imageView removeFromSuperview];
                }];
                return;
            }
        }
    }
    if (_clickView) {
        frame = [_clickView.superview convertRect:_clickView.frame toView:_superView];
    }
    UIImageView *imageView=[[UIImageView alloc]initWithFrame:image.frame];
    imageView.contentMode=UIViewContentModeScaleAspectFit;
    imageView.image=((UIImageView*)_clickView).image;
    [self removeFromSuperview];
    if (self.clickView) {
        [_superView addSubview:imageView];
        
    }else{
        imageView.image=image.image;
        [[[[UIApplication sharedApplication] delegate] window] addSubview:imageView];
    }
    
    WJCWeakSelf
    [UIView animateWithDuration:0.3 animations:^{
        if (weakSelf.clickView) {
            imageView.frame=frame;
        }else{
            image.frame=CGRectMake(WJCScreenW*0.5-20, WJCScreenH*0.5-20, 40, 40);
        }
        
    }completion:^(BOOL finished) {
        [imageView removeFromSuperview];
        [self removeFromSuperview];
    }];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _imageArr.count;
}


- ( UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    imageCollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:[NSString stringWithFormat:@"imageCell%ld",indexPath.row] forIndexPath:indexPath];
    cell.imageView.contentMode =  UIViewContentModeScaleAspectFit;
//    [cell.contentView removeChildViews];
    [cell.imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.equalTo(cell.contentView);
        make.top.equalTo(cell.contentView);
        make.bottom.equalTo(cell.contentView.mas_bottom);
    }];
    if(!cell.imageView){
        cell.imageView=[UIImageView new];
        [cell.contentView addSubview:cell.imageView];
        
    }
    if ([_imageArr[indexPath.row] isKindOfClass:[UIImage class]]) {
        cell.imageView.image=_imageArr[indexPath.row];
    }
    if ([_imageArr[indexPath.row] isKindOfClass:[NSString class]]) {
        UIImage *image=[WJCDeployModel getDeployWithDeployKey:WJCDeployImageHeadUrl];
        if (_smalllImage.count==self.imageArr.count) {
            if ([_smalllImage[indexPath.row] isKindOfClass:[UIImage class]]) {
                image=_smalllImage[indexPath.row];
            }
        }
        if (_page==indexPath.row) {
            image=((UIImageView*)_clickView).image;
        }
        if ([_imageArr[indexPath.row] isKindOfClass:[UIImage class]]) {
            cell.imageView=_imageArr[indexPath.row];
        }else{
            [cell.imageView  fc_setImageWithURL:_imageArr[indexPath.row] placeholder:image completed:^(UIImage *image) {
                CGFloat fixelH = CGImageGetHeight(cell.imageView.image.CGImage);
                CGFloat fixelW = CGImageGetWidth(cell.imageView.image.CGImage);
                if (fixelH>WJCScreenH&&fixelH>fixelW*2) {
                    [cell.imageView mas_remakeConstraints:^(MASConstraintMaker *make) {
//                        make.left.and.top.mas_equalTo(0);
                        make.width.mas_equalTo(WJCScreenW);
                        make.centerY.mas_equalTo(WJCScreenH*0.5);
                        make.height.mas_equalTo(fixelH*( WJCScreenW/fixelW));
                    }];
                }
            }];
//            [cell.imageView sd_setImageWithURL:[NSURL URLWithString:_imageArr[indexPath.row]] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
//
//            }];
                //        [cell.imageView sd_setImageWithURL:[NSURL URLWithString:_imageArr[indexPath.row]] placeholderImage:image options:SDWebImageProgressiveDownload progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
                ////                dispatch_async(dispatch_get_main_queue(), ^(void) {
                ////                     [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
                ////                });
                //        } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                //            [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
                //            CGFloat fixelH = CGImageGetHeight(cell.imageView.image.CGImage);
                //            CGFloat fixelW = CGImageGetWidth(cell.imageView.image.CGImage);
                //            if (fixelH>WJCScreenH&&fixelH>fixelW*2) {
                //                [cell.imageView mas_remakeConstraints:^(MASConstraintMaker *make) {
                //                    make.left.and.top.mas_equalTo(0);
                //                    make.width.mas_equalTo(WJCScreenW);
                //                    make.height.mas_equalTo(fixelH*( WJCScreenW/fixelW));
                //                }];
                //            }
                //
                //        }];
        }
        
    }
    cell.imageView.userInteractionEnabled=YES;
        // pinch手势实现 缩放
    UIPinchGestureRecognizer *pinch1 = [[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(pinch:)];
    [cell.imageView addGestureRecognizer:pinch1];
    
        //1. pan 拖拽手势 控制图片 位移
    UIPanGestureRecognizer *pan1 = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(pan:)];
    pan1.delegate=self;
    cell.imageView.tag=indexPath.row;
    [pan1 requireGestureRecognizerToFail:pinch1];
    [cell.imageView addGestureRecognizer:pan1];
    
    UITapGestureRecognizer *tap1=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap:)];
    tap1.numberOfTapsRequired=2;
    [cell.imageView addGestureRecognizer:tap1];
    UITapGestureRecognizer *tapp1=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap:)];
    [tapp1 requireGestureRecognizerToFail:tap1];
    [cell.imageView addGestureRecognizer:tapp1];
        //    创建手势
    UILongPressGestureRecognizer *longPress1 = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPress:)];
    longPress1.minimumPressDuration = 0.5;
    [longPress1 requireGestureRecognizerToFail:tap1];
    [cell.imageView addGestureRecognizer:longPress1];
    
    return cell;
    
}
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
        //     UIView *targetV;
        //    for (UIView *view in scrollView.subviews) {
        //
        //        if (view.subviews.count>0) {
        //            for (UIView *v in view.subviews) {
        //                if (v.tag ==self.page) {
        //                    targetV=v;
        //                }
        //            }
        //        }
        //        else if (view.tag ==self.page) {
        //            targetV=view;
        //        }
        //
        //    }
    float pageWidth = WJCScreenW; // width + space
    
    float currentOffset = scrollView.contentOffset.x;
    float targetOffset = targetContentOffset->x;
    float newTargetOffset = 0;
    
    if (targetOffset > currentOffset)
        newTargetOffset = ceilf(currentOffset / (pageWidth+10)) * (pageWidth+10);
    else
        newTargetOffset = floorf(currentOffset / (pageWidth+10)) * (pageWidth+10);
    
    if (newTargetOffset < 0)
        newTargetOffset = 0;
    else if (newTargetOffset > scrollView.contentSize.width)
        newTargetOffset = scrollView.contentSize.width;
    
    targetContentOffset->x = currentOffset;
    if (currentOffset==newTargetOffset) {
        return;
    }
    [scrollView setContentOffset:CGPointMake(newTargetOffset, 0) animated:YES];
    
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    int currentPageNum = round(scrollView.contentOffset.x /(WJCScreenW+10));
    if (currentPageNum!=self.page) {
        for (int i=0; i<_imageArr.count; i++) {
            NSIndexPath *index=[NSIndexPath indexPathForRow:i inSection:0];
            imageCollectionViewCell *cell=[_collection dequeueReusableCellWithReuseIdentifier:[NSString stringWithFormat:@"imageCell%d",i] forIndexPath:index];
            CGFloat fixelH = CGImageGetHeight(cell.imageView.image.CGImage);
            CGFloat fixelW = CGImageGetWidth(cell.imageView.image.CGImage);
            if (fixelH>WJCScreenH&&fixelH>fixelW*2) {
                cell.imageView.frame=CGRectMake(0, 0, WJCScreenW, fixelH*( WJCScreenW/fixelW));
            }
            else
                cell.imageView.frame=CGRectMake(0, 0, WJCScreenW, WJCScreenH);
        }
    }
    self.page=currentPageNum;
    _label.text=[NSString stringWithFormat:@"%d/%ld",_page+1,_imageArr.count];
}
-(void)tap:(UITapGestureRecognizer*)sender {
    
    if (sender.state==UIGestureRecognizerStateEnded) {
        if (sender.numberOfTapsRequired==2) {
            if (sender.view.frame.size.width<WJCScreenW*2.5) {
                [UIView animateWithDuration:0.5 animations:^{
                    sender.view.frame = CGRectMake((WJCScreenW-sender.view.frame.size.width)*0.5,(WJCScreenH-sender.view.frame.size.height)*0.5,WJCScreenW*3,WJCScreenH*3);
                    sender.view.center=CGPointMake(WJCScreenW*0.5, WJCScreenH*0.5);
                }];
            }
            else{
                [UIView animateWithDuration:0.5 animations:^{
                    sender.view.frame = CGRectMake(sender.view.frame.origin.x,0,WJCScreenW,WJCScreenH);
                    sender.view.center=CGPointMake(WJCScreenW*0.5, WJCScreenH*0.5);
                }];
                
            }
        }
        else{
            if (sender.numberOfTapsRequired==3) {
                [self removeFromSuperview];
            }else{
                [self removeWithView:(UIImageView*)sender.view];
            }
        }
    }
}
CGRect initRect;
-(void)pan:(UIPanGestureRecognizer*)sender {
    if(sender.state == UIGestureRecognizerStateBegan){
        initRect=sender.view.frame;
    }
    if(sender.state == UIGestureRecognizerStateChanged){
        CGPoint translation = [sender translationInView:self];
        if (translation.y<0) {
            
        }
        if(sender.view.y>=0&&translation.y>0){
            self.alpha=(WJCScreenH-sender.view.y-1)/WJCScreenH;
        }
            //            if (sender.view.frame.size.width>WJCScreenW||(self.collection.contentOffset.x==(WJCScreenW+10)*sender.view.tag)) {
            //                if (((sender.view.x>10&&translation.x>0)||(sender.view.width+sender.view.x<WJCScreenW+10&&translation.x<0))&&!canMove) {
            //                    canMove=NO;
            //                    self.collection.scrollEnabled=YES;
            //                    return;
            //                }
            //                if(sender.view.frame.size.width>WJCScreenW&&sender.view.x>=0&&translation.x>0){
            //                    return;
            //                }
            //                    self.collection.scrollEnabled=NO;
        if (self.alpha<1) {
            self.alpha=(WJCScreenH-sender.view.y-1)/WJCScreenH;
        }
            //               if(((sender.view.x>0&&translation.x>0)||(sender.view.width+sender.view.x<WJCScreenW+10&&translation.x<0))){
            //                    if(sender.view.y>0&&translation.y>0){
            //                        self.alpha=(WJCScreenH-sender.view.y)/WJCScreenH;
            //                    }else
            //                        return;
            //
            //                }
        
            //                if(sender.view.height+sender.view.y<WJCScreenH) {
            //                    return;
            //                };
        if (sender.view.width<=WJCScreenW+2&&sender.view.height<=WJCScreenH+2) {
            if (translation.y>translation.x) {
                sender.view.width= WJCScreenW*(self.alpha<1?self.alpha:1);
                sender.view.height=WJCScreenH*(self.alpha<1?self.alpha:1);
            }
            
        }
        if (((sender.view.frame.size.width>WJCScreenW||sender.view.frame.size.height>WJCScreenH)&&(sender.view.frame.origin.x<0||sender.view.width+sender.view.x>WJCScreenW||sender.view.height+sender.view.y>WJCScreenH))||self.alpha<1) {
            if (self.alpha<1) {
                CGFloat x=translation.x;
                if (translation.x<0) {
                    x=-translation.x;
                }
                if (translation.y>0&&sender.view.y<10&&translation.y<x) {
                    return;
                }else{
                    sender.view.center = CGPointMake(sender.view.center.x+ translation.x,
                                                     sender.view.center.y + translation.y);
                }
            }else{
                if (sender.view.frame.origin.x>0) {
                    return;
                }
                if (sender.view.width+sender.view.x<WJCScreenW) {
                    return;
                }
                if (sender.view.height+sender.view.y<WJCScreenH&&translation.y>translation.x) {
                    return;
                }
            }
            [self.collection setContentOffset:CGPointMake((WJCScreenW+10)*sender.view.tag, 0)];
            sender.view.center = CGPointMake(sender.view.center.x+ translation.x,
                                             sender.view.center.y + translation.y);
            
        }
        [sender setTranslation:CGPointZero inView:self];
    }
    if(sender.state == UIGestureRecognizerStateEnded){
        self.collection.scrollEnabled=YES;
        UIWindow * window=[[[UIApplication sharedApplication] delegate] window];
        CGRect rect=[sender.view convertRect:sender.view.bounds toView:window];
        if (self.alpha>0.7) {
            if (sender.view.frame.size.width<WJCScreenW) {
                
                [UIView animateWithDuration:0.25 animations:^{
                    CGFloat fixelH = CGImageGetHeight(((UIImageView*)sender.view).image.CGImage);
                    CGFloat fixelW = CGImageGetWidth(((UIImageView*)sender.view).image.CGImage);
                    if (fixelH>WJCScreenH&&fixelH>fixelW*2) {
                        ((UIImageView*)sender.view).frame=CGRectMake(sender.view.x, sender.view.y, WJCScreenW, fixelH*( WJCScreenW/fixelW));
                    }
                    else
                        {
                        CGFloat fixelH = CGImageGetHeight(((UIImageView*)sender.view).image.CGImage);
                        CGFloat fixelW = CGImageGetWidth(((UIImageView*)sender.view).image.CGImage);
                        if (fixelH>WJCScreenH&&fixelH>fixelW*2) {
                            ((UIImageView*)sender.view).frame=CGRectMake(sender.view.x, sender.view.y, WJCScreenW, fixelH*( WJCScreenW/fixelW));
                        }
                        else{
                            ((UIImageView*)sender.view).frame=CGRectMake(0, 0, WJCScreenW,WJCScreenH);
                        }
                        
                        }
                }];
                
            }
            
            if (rect.size.height-WJCScreenH+rect.origin.y<0) {
                [UIView animateWithDuration:0.25 animations:^{
                    sender.view.y=WJCScreenH-rect.size.height;
                        //                 sender.view.height=initRect.size.height;
                        //                 sender.view.width=initRect.size.width;
                }];
            }
            if(sender.view.x>0){
                [UIView animateWithDuration:0.25 animations:^{
                    sender.view.x=0;
                    if (self.alpha>0.85) {
                        sender.view.y=0;
                    }
                }];
            }
            if(sender.view.y>0){
                [UIView animateWithDuration:0.25 animations:^{
                    if (self.alpha>0.7) {
                        [UIView animateWithDuration:0.25 animations:^{
                            sender.view.y=0;
                        }];
                        
                    }
                }];
            }
            if(sender.view.x<0&&sender.view.width+sender.view.x<WJCScreenW){
                [UIView animateWithDuration:0.25 animations:^{
                    sender.view.x=WJCScreenW-sender.view.width;
                }];
            }
        }
        if (self.alpha<0.7) {
            [self removeWithView:(UIImageView*)sender.view];
        }else{
            if (sender.view.y>0) {
                [UIView animateWithDuration:0.25 animations:^{
                    sender.view.y=0;
                    
                }];
            }
            self.alpha=1;
            
        }
        
    }
    [sender setTranslation:CGPointZero inView:self];
}
-(void)pinch:(UIPinchGestureRecognizer*)sender {
    CGFloat scale = sender.scale;
    sender.view.transform = CGAffineTransformScale(sender.view.transform, scale, scale);
    if (sender.state==UIGestureRecognizerStateEnded) {
            //        if (sender.view.frame.size.width<WJCScreenW*0.4) {
            //            [self removeSelf];
            //        }
        if (sender.view.frame.size.width<WJCScreenW) {
            
            [UIView animateWithDuration:0.25 animations:^{
                CGFloat fixelH = CGImageGetHeight(((UIImageView*)sender.view).image.CGImage);
                CGFloat fixelW = CGImageGetWidth(((UIImageView*)sender.view).image.CGImage);
                if (fixelH>WJCScreenH&&fixelH>fixelW*2) {
                    ((UIImageView*)sender.view).frame=CGRectMake(sender.view.x, sender.view.y, WJCScreenW, fixelH*( WJCScreenW/fixelW));
                }
                else
                    {
                    CGFloat fixelH = CGImageGetHeight(((UIImageView*)sender.view).image.CGImage);
                    CGFloat fixelW = CGImageGetWidth(((UIImageView*)sender.view).image.CGImage);
                    if (fixelH>WJCScreenH&&fixelH>fixelW*2) {
                        ((UIImageView*)sender.view).frame=CGRectMake(sender.view.x, sender.view.y, WJCScreenW, fixelH*( WJCScreenW/fixelW));
                    }
                    else{
                        if (sender.view.frame.size.width<WJCScreenW*0.5) {
                            [self removeWithView:(UIImageView*)sender.view];
                            return ;
                        }
                        ((UIImageView*)sender.view).frame=CGRectMake(0, 0, WJCScreenW,WJCScreenH);
                    }
                    
                    }
            }];
            
        }
        if (sender.view.frame.size.width>WJCScreenW*3) {
            [UIView animateWithDuration:0.25 animations:^{
                ((UIImageView*)sender.view).frame=CGRectMake(sender.view.x, sender.view.y, WJCScreenW*3,WJCScreenH*3);
                sender.view.center=CGPointMake(WJCScreenW*0.5, WJCScreenH*0.5);
                sender.view.width=WJCScreenW*3;
                sender.view.height= WJCScreenH*3;
                
            }];
            
        }
        if (sender.view.frame.origin.x>0) {
            [UIView animateWithDuration:0.25 animations:^{
                sender.view.x=0;
                
            }];
            
            
        }
    }
        //把前一次 看成1个单位
    sender.scale = 1;
}
-(void)longPress:(UILongPressGestureRecognizer*)sender{
    
//    WJCWeakSelf
//    UIImageView *image = (UIImageView *)sender.view;
//    if (sender.state == UIGestureRecognizerStateBegan) {
//
//        UIAlertController *alert = [UIAlertController alertControllerWithTitle:approvallocaChanged(@"common_select_operation_please", @"请选择操作") message:nil preferredStyle:UIAlertControllerStyleAlert];
//            //2.创建AlertAction
//        UIAlertAction *action1 = [UIAlertAction actionWithTitle:approvallocaChanged(@"global_general_cancel",@"取消") style:UIAlertActionStyleCancel handler:nil];
//        UIAlertAction *action3 = [UIAlertAction actionWithTitle:approvallocaChanged(@"common_emun_save_picture", @"保存图片") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//                //            WJCLog(@"%ld",[sender view].tag);
//            UIImageView *image = (UIImageView *)sender.view;
//            UIImageWriteToSavedPhotosAlbum(image.image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
//        }];
//        UIAlertAction *action4 = [UIAlertAction actionWithTitle:approvallocaChanged(@"common_collect_pictures", @"收藏图片") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//            if([self.imageArr[_page] isKindOfClass:[UIImage class]]){
//                [SVProgressHUD showErrorWithStatus:approvallocaChanged(@"无法收藏非网络图片", nil)];
//                return ;
//            }
//            if(!weakSelf.collectionBlock){
//                [SVProgressHUD showErrorWithStatus:approvallocaChanged(@"该图片不支持图片", nil)];
//                return ;
//            }
//            weakSelf.collectionBlock(self.imageArr[_page]);
//
//        }];
//        UIAlertAction *action2 = [UIAlertAction actionWithTitle:approvallocaChanged(@"common_forward_pictures", @"转发图片") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//
//            if (weakSelf.UserInfo.Id.length) {
//
//                [self removeWithView:(UIImageView*)sender.view];
//
//                UITabBarController *tabbarVc = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
//                UINavigationController *nav = (UINavigationController *)tabbarVc.selectedViewController;
//
//                FCChoiceFriendViewController *teamVc=[FCChoiceFriendViewController new];
//                teamVc.returnBlock = ^(NSArray *choiceData) {
//                    NSMutableArray *uids = [NSMutableArray array];
//                    NSString *currentUserId = [[NIMSDK sharedSDK].loginManager currentAccount];
//                    [uids addObject:currentUserId];
//                    for (int i=0; i<choiceData.count; i++) {
//                        if ([choiceData[i] isKindOfClass:[NIMRecentSession class]]) {//最近会话列表选择的
//                            [FCForwardMessageTool sendMessageWithMessageType:ForwardMessageTypeImage andMessageData:image.image andSession:((NIMRecentSession*)choiceData[i]).session];
//                        }
//                        else if ([choiceData[i] isKindOfClass:[FCEmployeeModel class]]){//员工列表选择的
//
//                            [FCForwardMessageTool forwardMessageWithEmployeesAndTeams:@[choiceData[i]] andMessageType:ForwardMessageTypeImage andMessageData:image.image andSessionType:NIMSessionTypeP2P];
//                        }
//                        else if ([choiceData[i] isKindOfClass:[WJCFriendsModel class]]){//hao'yo列表选择的
//                            [FCForwardMessageTool forwardMessageWithEmployeesAndTeams:@[((WJCFriendsModel*)choiceData[i]).Friend] andMessageType:ForwardMessageTypeImage andMessageData:image.image andSessionType:NIMSessionTypeP2P];
//                        }
//                        else if ([choiceData[i] isKindOfClass:[NIMTeam class]]){//hao'yo列表选择的
//                            [FCForwardMessageTool forwardMessageWithEmployeesAndTeams:@[((NIMTeam*)choiceData[i])] andMessageType:ForwardMessageTypeImage andMessageData:image.image andSessionType:NIMSessionTypeTeam];
//                        }
//                    }
//                    [SVProgressHUD showSuccessWithStatus:approvallocaChanged(@"global_share_errcode_success",@"分享成功")];
//                };
//                [nav pushViewController:teamVc animated:YES];
//                    //                WJCRorwardTableViewController *bidding = [[WJCRorwardTableViewController alloc] init];
//                    //                [nav pushViewController:bidding animated:YES];
//                    //                bidding.returnBlock=^(NSArray<FCEmployeeModel *>* employees){
//                    //
//                    //                    [FCForwardMessageTool forwardMessageWithEmployeesAndTeams:employees andMessageType:ForwardMessageTypeImage andMessageData:image.image andSessionType:NIMSessionTypeP2P];
//                    //                };
//                    //
//                    //                bidding.returnTeamBlock=^(NSArray<NIMTeam *>* teams){
//                    //
//                    //                    [FCForwardMessageTool forwardMessageWithEmployeesAndTeams:teams andMessageType:ForwardMessageTypeImage andMessageData:image.image andSessionType:NIMSessionTypeTeam];
//                    //                };
//
//            } else {
//
//                WJCalertWarn *wjcAlert = [WJCalertWarn new];
//                [weakSelf addSubview:wjcAlert];
//                wjcAlert.loginLaterClickBlock=^(UIButton *button,WJCalertWarn *view){
//                    [view removeFromSuperview];
//                };
//                wjcAlert.loginClickBlock=^(UIButton *button,WJCalertWarn *view){
//                    [view removeFromSuperview];
//                    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"WJCLoginView" bundle:nil];
//                    [UIApplication sharedApplication].keyWindow.rootViewController = storyboard.instantiateInitialViewController;
//                };
//
//            }
//
//        }];
//        CIDetector*detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:@{ CIDetectorAccuracy : CIDetectorAccuracyHigh }];
//            //2. 扫描获取的特征组
//        NSArray *features;
//        @try{
//            features = [detector featuresInImage:[CIImage imageWithCGImage:image.image.CGImage]];
//        }
//        @catch(NSException *exception){
//            [MyUncaughtExceptionHandler upErrorWithDic:@{@"图片长安崩溃":exception} andTraceEvent:Start];
//        }
//        @finally{
//                //3. 获取扫描结果
//            if (features.count>0) {
//                CIQRCodeFeature *feature = [features objectAtIndex:0];
//                NSString *qrCodeStr = feature.messageString;
//                if (qrCodeStr.length>1) {
//                    UIAlertAction *action5 = [UIAlertAction actionWithTitle:approvallocaChanged(@"common_emun_identify_qr_code",@"识别二维码") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//                        if ([qrCodeStr containsString:@"http://"] || [qrCodeStr containsString:@"https://"]) {
//                            if ([qrCodeStr containsString:@"http://m.fccn.cc/company/profile"]||[qrCodeStr containsString:@"http://m.fccn.cc/user/profile"]) {
//                                NSRange range = [qrCodeStr rangeOfString:@"profile/"];
//                                NSString *str=[[NSString alloc]init];
//                                str=[qrCodeStr substringFromIndex:range.location+8];
//                                if ([qrCodeStr containsString:@"http://m.fccn.cc/company/profile"]) {
//
//                                    [XMGCompanyRequestAPI getCompanyInfoWithCompanyId:str andFields:@"Employees.User,Categories.Parent,Employees.RelationshipOfUs,Employees.Company.Categories,Employees.FriendOfUs.Group" andSuccess:^(FCCompanyModel *Company) {
//                                        dispatch_async(dispatch_get_main_queue(), ^{
//
//                                            [self removeWithView:(UIImageView*)sender.view];
//
//                                            UITabBarController *tabbarVc = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
//                                            UINavigationController *nav = (UINavigationController *)tabbarVc.selectedViewController;
//                                            [FCCompanyCardTool pushCompanyCardWithCompanyModel:Company andNavigation:nav];
//                                        });
//                                    } orFalse:^(NSError *error) {
//                                        if (error.code==404) {
//                                            [SVProgressHUD showErrorWithStatus:approvallocaChanged(@"global_ios_prompt3_ninety_six",@"未找到数据,请尝试重新操作")];
//                                        }
//                                        if (error.code==401) {
//                                            [SVProgressHUD showErrorWithStatus:approvallocaChanged(@"global_ios_prompt_five",@"您没有权限操作")];
//                                        }
//                                        if (error.code==0) {
//                                            [SVProgressHUD showErrorWithStatus:approvallocaChanged(@"global_ios_prompt_six",@"请检查网络是否开启")];
//                                        }
//                                        else showSVProgressErrorMessage;
//                                    }];
//                                    return;
//                                }
//                                else if([qrCodeStr containsString:@"http://m.fccn.cc/user/profile"]){
//
//                                    XMGDetailsCardController * friend=[XMGDetailsCardController new];
//                                    [XMGEmployesAPI getEmployeesInCompanyInformationWithEmployeeId:str andFields:@"RelationshipOfUs,Company,User,Company.Categories,FriendOfUs.Group,PrivacySettings" andMeId:[FCEmployeeModel getMinieEmpId] andSuccess:^(FCEmployeeModel *employees) {
//                                        dispatch_async(dispatch_get_main_queue(), ^{
//                                            [SVProgressHUD dismiss];
//                                            if (employees.RelationshipOfUs ==2) {
//                                                friend.isFriend=YES;
//
//                                            }
//                                            friend.employee=employees;
//                                            [self removeWithView:(UIImageView*)sender.view];
//                                            UITabBarController *tabbarVc = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
//                                            UINavigationController *nav = (UINavigationController *)tabbarVc.selectedViewController;
//                                            [nav pushViewController:friend animated:YES];
//                                        });
//                                    } orFalse:^(NSError *error) {
//                                        dispatch_async(dispatch_get_main_queue(), ^{
//                                            if (error.code==404) {
//                                                [SVProgressHUD showErrorWithStatus:approvallocaChanged(@"global_ios_prompt3_ninety_six",@"未找到数据,请尝试重新操作")];
//                                            }
//                                            if (error.code==401) {
//                                                [SVProgressHUD showErrorWithStatus:approvallocaChanged(@"global_ios_prompt_five",@"您没有权限操作")];
//                                            }
//                                            if (error.code==0) {
//                                                [SVProgressHUD showErrorWithStatus:approvallocaChanged(@"global_ios_prompt_six",@"请检查网络是否开启")];
//                                            }
//                                            else{
//                                                [SVProgressHUD showErrorWithStatus:error.userInfo[@"Message"]];
//                                            }
//                                        });
//                                    }];
//                                    return;
//                                }
//
//                            } else if ([qrCodeStr containsString:@"corpsite.fccn.cc"] || [qrCodeStr containsString:@"corpsitedev.fccn.cc"]) {
//
//                                NSString *containsString = @"corpsite.fccn.cc/";
//                                if ([qrCodeStr containsString:@"corpsitedev.fccn.cc"]) {
//                                    containsString = @"corpsitedev.fccn.cc/";
//                                }
//
//                                NSRange range = [qrCodeStr rangeOfString:containsString];
//                                NSString *result1  = [qrCodeStr substringFromIndex:range.location + containsString.length];
//
//                                NSMutableDictionary *param = [NSMutableDictionary dictionary];
//                                param[@"tree"] = @"true";
//                                param[@"fields"] = @"Company";
//
//                                [SVProgressHUD show];
//                                [FCBrandSiteRequest getCompanySitesWithCompanyId:result1 andParam:param success:^(FCCompanySiteModel *result) {
//                                    [SVProgressHUD dismiss];
//                                    [self removeWithView:(UIImageView*)sender.view];
//
//                                    UITabBarController *tabbar = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
//                                    UINavigationController *nav = (UINavigationController *)tabbar.selectedViewController;
//
//                                    [FCCompanyCardTool pushBrandSiteWithBrandSiteModel:result andNavigation:nav];
//
//                                } failure:^(NSError *error) {
//                                    [SVProgressHUD dismiss];
//                                        //                                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:qrCodeStr]];
//                                }];
//
//                                return;
//                            }
//
//                            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:qrCodeStr]];
//
//                        } else {
//                                //取出数据
//                            NSData *data=[qrCodeStr dataUsingEncoding:NSUTF8StringEncoding];
//                            NSError *error;
//                            NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
//                            if (!error) {
//
//                                if ([dic[@"type"] intValue] ==0) {
//                                    [SVProgressHUD show];
//                                    XMGDetailsCardController * friend=[XMGDetailsCardController new];
//                                    [XMGEmployesAPI getEmployeesInCompanyInformationWithEmployeeId:dic[@"data"][@"userId"] andFields:@"RelationshipOfUs,Company,User,Company.Categories,FriendOfUs.Group,PrivacySettings" andMeId:[FCEmployeeModel getMinieEmpId] andSuccess:^(FCEmployeeModel *employees) {
//                                        dispatch_async(dispatch_get_main_queue(), ^{
//                                            [SVProgressHUD dismiss];
//                                            if (employees.RelationshipOfUs ==2) {
//                                                friend.isFriend=YES;
//
//                                            }
//                                            friend.employee=employees;
//                                            UITabBarController *tabbarVc = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
//                                            UINavigationController *nav = (UINavigationController *)tabbarVc.selectedViewController;
//                                            [self removeWithView:(UIImageView*)sender.view];
//                                            [nav pushViewController:friend animated:YES];
//                                        });
//                                    } orFalse:^(NSError *error) {
//                                        dispatch_async(dispatch_get_main_queue(), ^{
//                                            if (error.code==404) {
//                                                [SVProgressHUD showErrorWithStatus:approvallocaChanged(@"global_ios_prompt3_ninety_six",@"未找到数据,请尝试重新操作")];
//                                            }
//                                            if (error.code==401) {
//                                                [SVProgressHUD showErrorWithStatus:approvallocaChanged(@"global_ios_prompt_five",@"您没有权限操作")];
//                                            }
//                                            if (error.code==0) {
//                                                [SVProgressHUD showErrorWithStatus:approvallocaChanged(@"global_ios_prompt_six",@"请检查网络是否开启")];
//                                            }
//                                            else{
//                                                [SVProgressHUD showErrorWithStatus:error.userInfo[@"Message"]];
//                                            }
//                                        });
//                                    }];
//
//                                }
//                                if ([dic[@"type"] intValue] ==1){
//                                    if (![FCEmployeeModel getMinieCompanyId]) {
//
//                                        [SVProgressHUD showErrorWithStatus:approvallocaChanged(@"global_ios_prompt_not_join_team_person", @"个人用户无法加入群聊")];
//                                        return;
//                                    }
//
//                                    [[NIMSDK sharedSDK].teamManager applyToTeam:dic[@"data"][@"userId"] message:@"申请加入" completion:^(NSError * _Nullable error, NIMTeamApplyStatus applyStatus) {
//
//                                        if (!error) {
//
//                                            NIMSession *session = [NIMSession session:dic[@"data"][@"userId"] type:NIMSessionTypeTeam];
//                                            WJCTalkViewController *vc = [[WJCTalkViewController alloc] initWithSession:session];
//                                            UITabBarController *tabbarVc = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
//                                            UINavigationController *nav = (UINavigationController *)tabbarVc.selectedViewController;
//                                            [self removeWithView:(UIImageView*)sender.view];
//                                            [nav pushViewController:vc animated:YES];
//
//                                        } else {
//                                            [SVProgressHUD showErrorWithStatus:[NSString outPutNimErrorWithErrorCode:error.code]];
//                                                //                                    if (error.code == 809) {
//                                                //
//                                                //                                        [SVProgressHUD showErrorWithStatus:@"您已经在群里"];
//                                                //
//                                                //                                    } else if (error.code == 801) {
//                                                //
//                                                //                                        [SVProgressHUD showErrorWithStatus:@"群人数达到上限"];
//                                                //
//                                                //                                    } else if (error.code == 803) {
//                                                //
//                                                //                                        [SVProgressHUD showErrorWithStatus:@"群不存在"];
//                                                //
//                                                //                                    } else {
//                                                //                                        [SVProgressHUD showErrorWithStatus:@"没有权限"];
//                                                //
//                                                //                                    }
//
//                                        }
//
//
//                                    }];
//                                        //                            FCAdvancedTeamCardViewController *advan=[[FCAdvancedTeamCardViewController alloc]initWithTeam:[[NIMSDK sharedSDK].teamManager teamById:dic[@"data"][@"userId"]]];
//                                        ////                            [self.navigationController pushViewController:advan animated:YES];
//                                        //                            UITabBarController *tabbarVc = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
//                                        //                            UINavigationController *nav = (UINavigationController *)tabbarVc.selectedViewController;
//                                        //                            [weakSelf removeSelf];
//                                        //                            [nav pushViewController:advan animated:YES];
//
//                                }
//                                    //            XMGDetailedInformationController *addFriend=[XMGDetailedInformationController new];
//                                    //            if (dic[@"data"][@"userId"]) {
//                                    //                self.hud.label.text=@"扫描添加好友";
//                                    //                NSDictionary *employDic=[XMGEmployesAPI getEmployeesInCompanyInformationWithEmployeeId:dic[@"data"][@"userId"] andFields:@"RelationshipOfUs,Company" andMeId:[FCEmployeeModel getMinieEmpId]];
//                                    //                if ([employDic[@"RelationshipOfUs"] intValue]==2) {
//                                    //                    addFriend.Type=YES;
//                                    //                    addFriend.accId=employDic[@"AccId"];
//                                    //                }
//                                    //                [self.navigationController pushViewController:addFriend animated:YES];
//                                    //
//                                    //            }
//                                    //            else{
//                                    //                self.hud.label.text=@"扫描错误";
//                                    //                self.hud.detailsLabel.text=@"二维码格式错误,请扫描用户的二维码";
//                                    //                dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC));
//                                    //                dispatch_after(delayTime, dispatch_get_main_queue(), ^{
//                                    //                    progressHudHide;
//                                    //                    [self.navigationController popViewControllerAnimated:YES];
//                                    //                });
//                                    //
//                                    //            }
//                                    //           [XMGAddNewFriendAPI addFriendAPIWithsenderID:[FCEmployeeModel getMinieEmpId] andreceiverID:dic[@"data"][@"userId"] andGroupId:nil andrequestMsg:@"请求添加好友" andFields:nil];
//                            }
//                            else{
//                                [SVProgressHUD showErrorWithStatus:approvallocaChanged(@"扫描数据出错", nil)];
//                            }
//                        }
//
//                    }];
//                    [alert addAction:action5];
//                }
//            }
//                //3.将 AlertAction 添加到 AlertController中
//            [alert addAction:action1];
//            [alert addAction:action2];
//            [alert addAction:action3];
//            [alert addAction:action4];
//            [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alert animated:YES completion:nil];
//        }
//
//
//    } else if (sender.state == UIGestureRecognizerStateEnded) {
//        WJCLog(@"长按结束");
//
//    }
}
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
}

#pragma mark - UICollectionViewDelegateFlowLayout

    //- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    //    [self removeFromSuperview];
    //}

- (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo
{
    if(error != NULL){
//        [SVProgressHUD showErrorWithStatus:approvallocaChanged(@"global_ios_save_failure",@"保存失败")];
    }else{
        
//        [SVProgressHUD showSuccessWithStatus:approvallocaChanged(@"global_general_save_succeed",@"保存成功")];
    }
}


@end
